<template>
	<div class="trainSeat train">
		<trainHeader name="车次详情"></trainHeader>
		<template v-if="isShowFlag">
			<div v-if="sectionObj" class="trainSeat_section">
				建议您购买（{{sectionObj.fromStation}}-{{sectionObj.endStation}}）的车票，您可持票在{{sectionObj.fromCity}}上车，
				<span v-if="sectionObj.price">全程多花约{{sectionObj.price}}元！</span>
				<span v-else>上车后联系乘务员补至{{sectionObj.toStation}}！</span>
			</div>
			<trainlistdetails :msg=msg :departureDate=departureDate v-if="msg"></trainlistdetails>
			<!--日期-->
			<div class="trainSeat_box" v-if="!sectionObj">
				<div class="trainSeat_dateMsg">
					<div @click="preday" :class="{'trainSeat_day_old' : departureDateMsg.isToday}">前一天</div>
					<router-link :to="'/train/date?departureDate=' + departureDate + '&isChangTicket=' + Number(isChangTicket)">
						<div class="trainSeat_date" v-if="departureDateMsg">
							<div class="trainSeat_date_font">
								<span class="trainSeat_date_msg">{{departureDateMsg.day}}</span>
								<span v-if="departureDateMsg.isToday">今天</span>
								<span v-else-if="departureDateMsg.isTomorrow">明天</span>
								<span v-else>{{departureDateMsg.week}}</span>
							</div>
							<div class="trainSeat_pic">
								<img src="../../../assets/rili.png" alt="" />
							</div>
						</div>
					</router-link>
					<div @click="nextday" :class="{'trainSeat_day_old' : endDate == departureDate}">后一天</div>
				</div>
			</div>
			<div v-if="isTrainNo">
				<!--预约提示-->
				<div class="trainSeat_tip" v-if="msg.note">
					<span v-if="(msg.saleFlag == '2' || msg.saleFlag == '3') && advanceDate.trainQPvanceDays">{{msg.note}},现可预约抢票</span>
					<span v-else>{{msg.note}}</span>
				</div>
				<!--座位信息-->
				<div class="trainSeat_seat">
					<div v-for="item in msg.ticketsArr" class="trainSeat_seat_content">
						<!--座位-->
						<div class="trainSeat_seat_seatName">{{item.seatName}}</div>
						<!--钱-->
						<div class="trainSeat_seat_money">
							￥<span>{{item.lowestPrice}}</span>
							<span v-if="HCCashBackFlag" v-show="item.lowestPrice > 3.6" class="trainSeat_seat_returnMoney">返{{item.lowestPrice | returnMoney}}</span>
						</div>
						<!--票的数量-->
						<template v-if="((msg.saleFlag == '2' || msg.saleFlag == '3') && advanceDate.trainQPvanceDays) && !isChangTicket">
							<!--预约抢票-->
							<div class="trainSeat_seat_dateRob" @click="skipOrder(3,item)">
								<img src="http://h5.kpcx179.com/wximages/train/yuyueqiangpiao@2x.png" alt="" />
							</div>
						</template>
						<template v-else>
							<div class="trainSeat_seat_number">
								<div v-if="item.seats>0">
									<span v-if="item.seats<21" style="color: #fd6523;">仅剩{{item.seats}}张</span>
									<span v-else>有票</span>
								</div>
								<div v-else>
									无票
								</div>
							</div>
							<!--预定按钮-->
							<div class="trainSeat_seat_btn" :class="{'rob':item.seats<=0,'changTicket':(item.seats<=0 && isChangTicket)}">
								<div v-if="item.seats>0">
									<span v-if="isChangTicket" @click="skipOrder(2,item)">改签</span>
									<span v-else @click="skipOrder(1,item)">订票</span>
								</div>
								<div v-else>
									<span v-if="isChangTicket">改签</span>
									<span v-else @click="skipOrder(3,item)">抢票</span>
								</div>
							</div>
						</template>
					</div>
				</div>
				<!--区间查询-->
				<div class="trainSeat_inquire" v-if="!(msg.note || sectionObj || isChangTicket)">
					<div class="trainSeat_inquire_box" @click="inquire">
						<div class="trainSeat_inquire_font">
							<div>区间查询</div>
							<div class="trainSeat_inquire_msg">查询中间站/跨站余票</div>
						</div>
						<div>
							<img src="http://h5.kpcx179.com/wximages/train/gengduo-@2x.png" alt="" />
						</div>
					</div>
				</div>
			</div>
		</template>
	</div>
</template>
<style scoped>
	.trainSeat_section {
		padding: 19px 30px;
		font-size: 28px;
		background: rgb(250, 226, 218);
		color: rgb(251, 101, 35);
		line-height: 35px;
	}
	
	.trainSeat_box {
		padding: 0 17px;
		font-size: 26px;
		color: #3bc3c2;
	}
	
	.trainSeat_dateMsg {
		display: flex;
		height: 90px;
		width: 100%;
		padding: 0 13px;
		box-sizing: border-box;
		align-items: center;
		justify-content: space-between;
		background: #fff;
		border-radius: 0 0 10px 10px;
	}
	
	.trainSeat_date {
		display: flex;
		width: 290px;
		height: 60px;
		justify-content: center;
		align-items: center;
		border-radius: 8px;
		border: 2px solid #3bc3c2;
		font-size: 26px;
		color: #3bc3c2;
	}
	
	.trainSeat_date_msg {
		margin-right: 5px;
	}
	
	.trainSeat_pic {
		width: 57px;
		height: 42px;
		border-left: 2px solid #3bc3c2;
		display: flex;
		justify-content: center;
	}
	
	.trainSeat_date_font {
		display: flex;
		justify-content: space-between;
		padding: 0 11px 0 22px;
	}
	
	.trainSeat_pic>img {
		width: 40px;
		height: 40px;
	}
	
	.trainSeat_seat {
		margin: 0 17px;
		background-color: #fff;
		border-radius: 10px;
		margin-top: 20px;
	}
	
	.trainSeat_seat_content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 128px;
		border-bottom: 2px solid #c8c8c8;
		padding: 0 34px;
		font-size: 28px;
		color: #333;
	}
	
	.trainSeat_seat_content:last-child {
		border-bottom: 0;
	}
	
	.trainSeat_seat_money {
		color: #fb6523;
		width: 35%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.trainSeat_seat_money>span {
		font-size: 33px;
	}
	
	.trainSeat_seat_money>.trainSeat_seat_returnMoney {
		border: 2px solid rgb(251, 101, 35);
		padding: 5px 10px;
		border-radius: 10px;
		font-size: 20px;
		margin-left: 5px;
	}
	
	.trainSeat_seat_seatName {
		width: 17%;
		text-align: left;
	}
	
	.trainSeat_seat_number {
		width: 22%;
		text-align: center;
	}
	
	.trainSeat_seat_btn {
		width: 122px;
		height: 47px;
		text-align: center;
		line-height: 47px;
		background: linear-gradient(to right, #63e5d8, #3cc3c3);
		color: #fff;
		border-radius: 8px;
	}
	
	.trainSeat_seat_btn.rob {
		background: linear-gradient(to right, #fa8c51, #ff5a01);
	}
	
	.trainSeat_seat_content>.trainSeat_seat_btn.changTicket {
		background: #cacaca;
	}
	
	.trainSeat_tip {
		height: 70px;
		font-size: 28px;
		text-align: left;
		line-height: 70px;
		width: 100%;
		padding: 0 32px;
		box-sizing: border-box;
		color: #fb6523;
		background-color: #FAE2DA;
		margin-bottom: 10px;
		margin-top: -10px;
	}
	
	.trainSeat_seat_dateRob {
		width: 122px;
		height: 47px;
		flex: 1;
		display: flex;
		justify-content: flex-end;
	}
	
	.trainSeat_seat_dateRob>img {
		width: 122px;
		height: 47px;
	}
	
	.trainSeat_inquire {
		padding: 0 19px;
		margin-top: 20px;
		box-sizing: border-box;
		height: 92px;
	}
	
	.trainSeat_inquire_box {
		height: 92px;
		padding: 0 30px;
		background-color: #fff;
		border-radius: 10px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 28px;
		color: #333333;
	}
	
	.trainSeat_inquire_font {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}
	
	.trainSeat_inquire_msg {
		margin-left: 60px;
		color: #999999;
	}
	
	.trainSeat_inquire img {
		width: 20px;
		height: 34px;
	}
	
	.trainSeat_day_old {
		color: rgb(138, 138, 138);
	}
</style>
<script>
	import trainlistdetails from "../../../components/trainListDetails";
	import trainHeader from "../../../components/trainHeader";
	export default {
		data() {
			return {
				msg: null, //车次信息
				fromStation: "", //车站信息
				toStation: "",
				trainNo: "", //车次号
				departureDate: "", //发车日期
				departureDateMsg: "",
				advanceDate: "", //预售信息
				isTrainNo: true,
				isChangTicket: false, //是否改签
				endDate: "", //可购票的最后一天的日期
				sectionObj: null,
				queryKey: "", //请求key
				isShowFlag: false,
				studentFlag: false, //学生票
				HCCashBackFlag:false,//返现开关
			}
		},
		mounted() {
			var trainStore = this.$store.state.train.trainStore;
			if(trainStore.trainSeat) {
				var trainSeat = JSON.parse(JSON.stringify(trainStore.trainSeat));
				Object.keys(trainSeat).forEach(i => {
					this[i] = trainSeat[i];
				}, this);
			} else {
				this.isChangTicket = Boolean(Number(this.$route.query.isChangTicket));
				this.trainNo = this.$route.query.trainNo; //车次
				this.fromStation = this.$route.query.fromStation; //车站
				this.toStation = this.$route.query.toStation;
				this.studentFlag = Boolean(Number(this.$route.query.studentFlag)); //是否学生票
				if(trainStore.advanceDate) { //预售
					this.advanceDate = trainStore.advanceDate; //预售
					this.endDate = this.isChangTicket ? this.advanceDate.dateChange : this.advanceDate.date; //后一天的结束时间
				} else {
					this.advanceBook();
				};
				(trainStore.HCCashBackFlag) ? (this.HCCashBackFlag = Boolean(Number(trainStore.HCCashBackFlag))) : this.getInsurance();//返现开关
				trainStore.seatMessage && (this.msg = trainStore.seatMessage.msg);
				trainStore.seatMessage && (this.departureDateMsg = trainStore.seatMessage.departureDateMsg);
			};
			this.departureDate = (this.isChangTicket ? trainStore.changeMessage.departureDate : trainStore.departureDate) || this.$route.query.departureDate || new Date().format("yyyy-MM-dd"); //日期
		},
		methods: {
			getDepartureDate(flag) { //处理时间信息
				if (!this.msg) return;
				this.msg.startDate = this.$publicMethod.getWeek(this.departureDate + " " + this.msg.fromTime);
				this.msg.endDate = this.$publicMethod.getWeek(new Date(this.msg.startDate.dateMsg.getTime() + (this.msg.runTimeSpan * 60 * 1000)).format("yyyy-MM-dd hh:mm:ss"));
				this.departureDateMsg = this.$publicMethod.getWeek(this.departureDate);
				var trainStore = JSON.parse(JSON.stringify(this.$store.state.train.trainStore));
				trainStore.seatMessage = {
					msg:this.msg,
					departureDateMsg:this.departureDateMsg
				};
				this.$store.commit('TRAINSTORE', trainStore);	
//				this.msg = JSON.parse(JSON.stringify(this.msg));
			},
			getList() {
				this.$loading.show();
				this.isTrainNo = false;
				var param = {
					fromStation: encodeURI(this.sectionObj ? this.sectionObj.fromStation : this.fromStation),
					toStation: encodeURI(this.sectionObj ? this.sectionObj.endStation : this.toStation),
					ticketType: this.studentFlag ? 2 : 1, // 1正常票  2学生票  默认1
					trainDate: this.departureDate.replace(/-/g, ''),
				};
				this.$http.post(this.$baseUrl.baseurl + "tctrain/train/train", param).then((res) => {
					this.isShowFlag = true;
					if(res.data.Code == "0") {
						var list = res.data.Result.trains || [];
						var trainNo = this.trainNo;
						var middata = list.filter(function(elem) {
							return elem.trainNo == trainNo;
						});
						if(!middata.length) {
							this.$loading.hide();
							this.$toast("没有找到该车次", {
								durtaion: 200,
								location: 'center',
							});
							this.getDepartureDate(); //改日期
							this.msg && (this.msg.note = null);
							return;
						};
						var ticketsArr = []; //处理座次排序
						for(var item in middata[0].tickets) { //获取座位信息
							let obj = middata[0].tickets[item];
							obj.seatClass = item; //添加坐席代号
							ticketsArr.push(obj);
						};
						ticketsArr.sort((a, b) => { //根据价格排序
							var a = a.lowestPrice || a.price;
							var b = b.lowestPrice || b.price;
							return b - a;
						});
						if(ticketsArr.length > 1) { //处理无座和硬座/二等座价格相同的情况
							var flag = (ticketsArr[ticketsArr.length - 1].seatName == "硬座" || ticketsArr[ticketsArr.length - 1].seatName == "二等座") && (ticketsArr[ticketsArr.length - 2].seatName == "无座");
							if(flag) {
								let obj = ticketsArr[ticketsArr.length - 2];
								ticketsArr[ticketsArr.length - 2] = ticketsArr[ticketsArr.length - 1];
								ticketsArr[ticketsArr.length - 1] = obj;
							};
						};
						middata[0].ticketsArr = ticketsArr;
						this.msg = middata[0];
						this.queryKey = res.data.Result.queryKey;
						this.getDepartureDate();
						this.isTrainNo = true;
						this.$loading.hide();
					} else {
						this.$loading.hide();
						this.getDepartureDate(); //改日期
						this.msg.note = null;
						this.$toast("没有找到该车次", {
							durtaion: 200,
							location: 'center',
						});
					};
				}).catch((err) => {
					this.$loading.hide();
					console.log(err);
				});
			},
			preday() { //前一天
				var time = this.$publicMethod.getTimeFormat(this.departureDate).getTime();
				(new Date().getTime() > time) ? this.$toast("没有前一天了", {
					durtaion: 200,
					location: 'center',
				}): (this.departureDate = this.$publicMethod.getNowFormatDateAfter(-1, this.departureDate).format("yyyy-MM-dd"));
			},
			nextday() { //后一天				
				if(new Date(this.departureDate.replace(/-/g, '/')).getTime() < new Date(this.endDate.replace(/-/g, '/')).getTime()) {
					this.departureDate = this.$publicMethod.getNowFormatDateAfter(1, this.departureDate).format("yyyy-MM-dd");
				} else { // 没有后一天了
					var time = new Date(this.endDate.replace(/-/g, '/'));
					time = time.getMonth() + 1 + "月" + time.getDate() + "日";
					this.$toast('不能选择' + time + '后的日期哦', {
						durtaion: 200,
						location: 'center',
					});
				};
			},
			inquire() {
				var fromStation = encodeURI(this.msg.fromCity || this.msg.fromStation);
				var toStation = encodeURI(this.msg.toCity || this.msg.toStation);
				var trainNo = this.msg.trainNo ? this.msg.trainNo.split('|')[0] : this.msg.trainNum;
				var price = this.msg.ticketsArr[this.msg.ticketsArr.length - 1].price;
				this.$router.push({
					name: 'section',
					query: {
						fromStation,
						toStation,
						departureDate: this.departureDate,
						trainNo,
						price,
						studentFlag:Number(this.studentFlag),
					},
				});
			},
			skipOrder(sign, item) { //订单跳转
				if(this.$store.state.common.userinfo.userID) {
					if (this.$store.state.common.userinfo.realnamestatus) {
						var obj = {
							name: 'fillOrder',
							query: {
								trainNo: this.msg.trainNo || this.msg.trainNum,
								fromStation: this.msg.fromStation || this.msg.fromCity,
								toStation: this.msg.toStation || this.msg.toCity,
								departureDate: this.departureDate,
								ticketType: 0,
								seatMessage: JSON.stringify(item),
								studentFlag: Number(this.studentFlag),
								seats:item.seats,//坐席剩余数量
							},
						};
						if(sign == 1) { //普通单
							this.$router.push(obj);
						} else if(sign == 2) { //改签单
							obj.name = "trainChangeFillOrder";
							this.$router.push(obj);
						} else if(sign == 3) { //抢票单
//							var time = new Date(this.departureDate.replace(/-/g, '/') + ' ' + this.msg.fromTime + ':00').getTime(); //3小时以内不支持抢票
//							var now = new Date().getTime();
//							var distance = (time - now) / 1000 / 60 / 60;
//							(distance > 3) ? ((obj.query.ticketType = 1) && (this.$router.push(obj))) : this.$alert("由于您选的车次离发车时间太近，暂不支持抢票，建议您更换车次或者出发日期后再试");
							obj.query.ticketType = 1;
							this.$router.push(obj);
						};
					} else {
						this.payFlag || this.$alert({
							title: '提示',
							content:"应国家互联网信息办公室对于互联网实名制的要求，您需要先进行实名认证才可以预定",
							btnText:"去认证",
//							style:{
//								color:"rgb(68,68,68)",
//								fontWeight:200,
//							}
						}).then(() => {
							this.$router.push({
								path: '/my/modifyCard',
							});
						}).catch(() => {});
					};
				} else {
					this.$router.push({
						name: 'login',
					});
				};
			},
			advanceBook() { //预售查询
				this.$http.post(this.$baseUrl.baseurl + "tctrain/train/trainAdvanceTime", {}).then((res) => {
					var data = res.data.Result;
					var dayNum = Number(data.trainAdvanceDays) + Number(data.trainQPvanceDays);
					//替换@
					data.trainGQTips = data.trainGQTips.replace(/@/g, data.trainAdvanceDays);
					data.trainTips = data.trainTips.replace(/@/g, data.trainQPvanceDays);
					//存全局
					var trainStore = JSON.parse(JSON.stringify(this.$store.state.train.trainStore));
					trainStore.advanceDate = data;
					trainStore.advanceDate.dayNum = dayNum;
					trainStore.advanceDate.date = data.trainQPAdvanceTime;
					trainStore.advanceDate.dateChange = data.advanceTime;
					this.$store.commit('TRAINSTORE', trainStore);
					this.advanceDate = this.$store.state.train.trainStore.advanceDate; //预售
					this.endDate = this.isChangTicket ? this.advanceDate.dateChange : this.advanceDate.date; //后一天的结束时间
				}).catch((err) => {
					console.log(err);
				});
			},
			getInsurance() { //获取保险开关
				this.$http.post(this.$baseUrl.baseurl + "kpcx/switch/getAllSwitch", {
					"switch": "All",
				}).then((res) => {
					var trainStore = JSON.parse(JSON.stringify(this.$store.state.train.trainStore));
					trainStore.insuranceFlag = res.data.Result.activityInfo.Insure; //存到全局(0关1开)
					trainStore.HCCashBackFlag = res.data.Result.activityInfo.HCCashBack; //返现
					this.HCCashBackFlag = Boolean(Number(res.data.Result.activityInfo.HCCashBack));
					this.$store.commit('TRAINSTORE', trainStore); 
				}).catch((err) => {
					console.log(err);
				});
			},
		},
		created() {

		},
		watch: { //监听放置
			departureDate() { //首次进入使用页面传参不请求接口
				//this.isFirst ? (this.isFirst = false) : (this.getList());
				this.getList();
				var trainStore = JSON.parse(JSON.stringify(this.$store.state.train.trainStore));
				(this.isChangTicket) ? (trainStore.changeMessage.departureDate = this.departureDate) : (trainStore.departureDate = this.departureDate); //是否改签
				this.$store.commit('TRAINSTORE', trainStore);
			},
		},
		filters: { //过滤
			returnMoney(price){//返现
			    //该公式在价格为1.4时计算基本为0但由于保留一位小数所以在计算得0.09时也展示为0，因此判断为3.6时展示为0.1;
			    var money = (price / (20 + price / 50) * (Math.log(price) / Math.log(10))).toFixed(3);
			    money = money.substring(0,money.length-2);
			    (money.substring(money.length - 1) == 0) && (money = money.substring(0, money.length - 1));
			    money = + money;
			    (money > 30) && (money = 30); 
			    return money;
		  	},
		},
		components: {
			trainlistdetails,
			trainHeader
		},
		beforeRouteLeave(to, from, next) {
			var trainStore = JSON.parse(JSON.stringify(this.$store.state.train.trainStore));
			(to.name == "trainList") ? (trainStore.trainSeat = null) : (trainStore.trainSeat = this._data);
			(to.name == "fillOrder" && trainStore.fillOrder) && (trainStore.fillOrder = null);
			this.$store.commit('TRAINSTORE', trainStore);
			next();
		},
		computed: {}
	};
</script>